import React, { memo, useEffect, useMemo } from 'react';
import { Card, Row, Col, Button, Typography, Statistic, List, Empty, Spin } from 'antd';
import { 
  CalendarOutlined, 
  BookOutlined, 
  UserOutlined, 
  PlusOutlined,
  EyeOutlined,
  SettingOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useScheduleManagement, useScheduleStats } from '@/store/schedule';
import { useStudentManagement } from '@/store/student';
import { useCourseManagement } from '@/store/course';
import { getCurrentDate, isToday, formatDateForDisplay } from '@/utils/date';
import type { IScheduleInstance } from '@/types/schedule';
import type { IStudent } from '@/types/student';
import type { ICourse } from '@/types/course';
import styles from './HomePage.module.css';

const { Title, Text } = Typography;

/**
 * 首页组件
 * @description 显示课表概览、今日课程和快速操作功能
 */
const HomePage: React.FC = memo(() => {
  const navigate = useNavigate();
  
  // 状态管理
  const {
    instances,
    refresh: refreshSchedule
  } = useScheduleManagement();
  
  const {
    instanceStats
  } = useScheduleStats();
  
  const {
    students,
    fetchStudents
  } = useStudentManagement();
  
  const {
    courses,
    fetchCourses
  } = useCourseManagement();

  // 初始化数据
  useEffect(() => {
    const initializeData = async () => {
      try {
        await Promise.all([
          refreshSchedule(),
          fetchStudents(),
          fetchCourses()
        ]);
      } catch (error) {
        console.error('初始化首页数据失败:', error);
      }
    };

    initializeData();
  }, []); // 移除函数依赖，避免无限循环

  // 今日课程数据
  const todaySchedules = useMemo(() => {
    const today = getCurrentDate();
    return instances
      .filter(instance => instance.date === today)
      .sort((a, b) => a.startTime.localeCompare(b.startTime));
  }, [instances]);

  // 即将到来的课程（未来7天）
  const upcomingSchedules = useMemo(() => {
    const today = getCurrentDate();
    const nextWeek = new Date();
    nextWeek.setDate(nextWeek.getDate() + 7);
    const nextWeekStr = nextWeek.toISOString().split('T')[0];
    
    return instances
      .filter(instance => instance.date > today && instance.date <= nextWeekStr)
      .sort((a, b) => {
        const dateCompare = a.date.localeCompare(b.date);
        return dateCompare !== 0 ? dateCompare : a.startTime.localeCompare(b.startTime);
      })
      .slice(0, 5); // 只显示前5个
  }, [instances]);

  // 获取学生姓名
  const getStudentName = (studentId: string): string => {
    const student = students.find(s => s.id === studentId);
    return student?.name || '未知学生';
  };

  // 获取课程名称
  const getCourseName = (courseId: string): string => {
    const course = courses.find(c => c.id === courseId);
    return course?.name || '未知课程';
  };

  // 快速操作按钮
  const quickActions = [
    {
      key: 'add-student',
      title: '添加学生',
      icon: <UserOutlined />,
      onClick: () => navigate('/student?action=create')
    },
    {
      key: 'add-course',
      title: '添加课程',
      icon: <BookOutlined />,
      onClick: () => navigate('/course?action=create')
    },
    {
      key: 'add-schedule',
      title: '安排课程',
      icon: <CalendarOutlined />,
      onClick: () => navigate('/schedule?action=create')
    },
    {
      key: 'view-schedule',
      title: '查看课表',
      icon: <EyeOutlined />,
      onClick: () => navigate('/schedule')
    }
  ];

  // 渲染课程项
  const renderScheduleItem = (item: IScheduleInstance) => (
    <List.Item
      key={item.id}
      className={styles.scheduleItem}
      onClick={() => navigate(`/schedule?date=${item.date}&instance=${item.id}`)}
    >
      <div className={styles.scheduleItemContent}>
        <div className={styles.scheduleTime}>
          <Text strong>{item.startTime} - {item.endTime}</Text>
        </div>
        <div className={styles.scheduleInfo}>
          <Text className={styles.courseName}>{getCourseName(item.courseId)}</Text>
          <Text type="secondary" className={styles.studentName}>
            {getStudentName(item.studentId)}
          </Text>
        </div>
        {item.location && (
          <Text type="secondary" className={styles.location}>
            {item.location}
          </Text>
        )}
      </div>
    </List.Item>
  );

  const isLoading = false; // TODO: 从 store 中获取加载状态

  return (
    <div className={styles.homePage}>
      {/* 页面标题 */}
      <div className={styles.pageHeader}>
        <Title level={2} className={styles.pageTitle}>
          课程表管理系统
        </Title>
        <Text type="secondary">
          欢迎使用课程表管理系统，今天是 {formatDateForDisplay(getCurrentDate())}
        </Text>
      </div>

      <Spin spinning={isLoading}>
        {/* 统计卡片 */}
        <Row gutter={[16, 16]} className={styles.statisticsRow}>
          <Col xs={12} sm={6}>
            <Card className={styles.statisticCard}>
              <Statistic
                title="总学生数"
                value={students.length}
                prefix={<UserOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col xs={12} sm={6}>
            <Card className={styles.statisticCard}>
              <Statistic
                title="总课程数"
                value={courses.length}
                prefix={<BookOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          <Col xs={12} sm={6}>
            <Card className={styles.statisticCard}>
              <Statistic
                title="今日课程"
                value={todaySchedules.length}
                prefix={<CalendarOutlined />}
                valueStyle={{ color: '#faad14' }}
              />
            </Card>
          </Col>
          <Col xs={12} sm={6}>
            <Card className={styles.statisticCard}>
              <Statistic
                title="已完成"
                value={instanceStats.completed}
                prefix={<CalendarOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
        </Row>

        {/* 主要内容区域 */}
        <Row gutter={[16, 16]} className={styles.contentRow}>
          {/* 今日课程 */}
          <Col xs={24} lg={12}>
            <Card
              title={
                <div className={styles.cardTitle}>
                  <CalendarOutlined />
                  <span>今日课程</span>
                </div>
              }
              className={styles.todayScheduleCard}
              extra={
                <Button 
                  type="link" 
                  onClick={() => navigate('/schedule')}
                >
                  查看全部
                </Button>
              }
            >
              {todaySchedules.length > 0 ? (
                <List
                  dataSource={todaySchedules}
                  renderItem={renderScheduleItem}
                  className={styles.scheduleList}
                />
              ) : (
                <Empty
                  description="今日暂无课程安排"
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                />
              )}
            </Card>
          </Col>

          {/* 即将到来的课程 */}
          <Col xs={24} lg={12}>
            <Card
              title={
                <div className={styles.cardTitle}>
                  <CalendarOutlined />
                  <span>即将到来</span>
                </div>
              }
              className={styles.upcomingScheduleCard}
              extra={
                <Button 
                  type="link" 
                  onClick={() => navigate('/schedule')}
                >
                  查看全部
                </Button>
              }
            >
              {upcomingSchedules.length > 0 ? (
                <List
                  dataSource={upcomingSchedules}
                  renderItem={(item) => (
                    <List.Item
                      key={item.id}
                      className={styles.scheduleItem}
                      onClick={() => navigate(`/schedule?date=${item.date}&instance=${item.id}`)}
                    >
                      <div className={styles.scheduleItemContent}>
                        <div className={styles.scheduleDate}>
                          <Text strong>{formatDateForDisplay(item.date)}</Text>
                        </div>
                        <div className={styles.scheduleTime}>
                          <Text>{item.startTime} - {item.endTime}</Text>
                        </div>
                        <div className={styles.scheduleInfo}>
                          <Text className={styles.courseName}>{getCourseName(item.courseId)}</Text>
                          <Text type="secondary" className={styles.studentName}>
                            {getStudentName(item.studentId)}
                          </Text>
                        </div>
                      </div>
                    </List.Item>
                  )}
                  className={styles.scheduleList}
                />
              ) : (
                <Empty
                  description="暂无即将到来的课程"
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                />
              )}
            </Card>
          </Col>
        </Row>

        {/* 快速操作 */}
        <Card
          title={
            <div className={styles.cardTitle}>
              <PlusOutlined />
              <span>快速操作</span>
            </div>
          }
          className={styles.quickActionsCard}
        >
          <Row gutter={[16, 16]}>
            {quickActions.map(action => (
              <Col xs={12} sm={6} key={action.key}>
                <Button
                  type="dashed"
                  size="large"
                  icon={action.icon}
                  onClick={action.onClick}
                  className={styles.quickActionButton}
                  block
                >
                  {action.title}
                </Button>
              </Col>
            ))}
          </Row>
        </Card>
      </Spin>
    </div>
  );
});

HomePage.displayName = 'HomePage';

export default HomePage;